package tools.texture.controller {
	import kiwi.util.bitmap.BitmapUtil;

	import tools.model.EditorConfig;
	import tools.model.TileInfo;
	import tools.utils.MaxRectsBinPack;

	import org.robotlegs.mvcs.Command;

	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;

	/**
	 * 重建素材
	 * @author zhangming.luo
	 */
	public class RebuildTextureCommand extends Command {
		[Inject]
		public var config : EditorConfig;

		override public function execute() : void {
			// 合并
			var pack : MaxRectsBinPack = new MaxRectsBinPack(4096, 4096);
			var dic : Dictionary = new Dictionary();
			for each (var tile:TileInfo in config.allTileList) {
				var tmp : Rectangle = pack.insert(tile.source.width, tile.source.height, 0);
				dic[tile] = tmp;
			}
			var canvas : BitmapData = new BitmapData(4096, 4096, true, 0x0);
			for (var info:* in dic) {
				canvas.copyPixels(info.$source.bitmapData, info.source, dic[info].topLeft, null, null, true);
				info.source = dic[info];
			}
			canvas = BitmapUtil.trim(canvas, null);
			config.texture.bitmapData = canvas.clone();
		}
	}
}
